import utils from '../utils'

// Return integer rank of n (1-indexed) or 0 if pct <= 0 or n+1 if pct >= 1
function retainedPctToRank(pct, n) {
  let rank = null
  if (n === 0 || pct >= 1) {
    rank = 0
  } else if (pct <= 0) {
    rank = n + 1
  } else {
    rank = Math.floor((1 - pct) * (n + 2))
  }
  return rank
}

// nth (optional): sample every nth threshold (use estimate for speed)
function getThresholdByPct(pct, arcs, nth) {
  const tmp = arcs.getRemovableThresholds(nth)
  const rank = retainedPctToRank(pct, tmp.length)
  if (rank < 1) return 0
  if (rank > tmp.length) return Infinity
  return utils.findValueByRank(tmp, rank)
}

export default {
  getThresholdByPct,
}